package com.tledu.ssm.controller;

import com.tledu.ssm.core.config.UploadConfig;
import com.tledu.ssm.core.constants.CommonConstants;
import com.tledu.ssm.core.entity.AjaxResult;
import com.tledu.ssm.core.exception.LoginException;
import com.tledu.ssm.model.User;
import com.tledu.ssm.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author cyrus
 */
@Controller
@RequestMapping("/user")
@AllArgsConstructor
@Log4j
public class UserController {

    private final IUserService userService;

    private final UploadConfig uploadConfig;

    @GetMapping("list")
    public String list(User user, Model model) {
        List<User> list = userService.list(user);
        model.addAttribute("list", list);
        return "user/list";
    }

    @PostMapping(value = "login", params = {"username", "password"})
    @ResponseBody
    public AjaxResult<User> login(String username, String password, HttpSession session) throws LoginException {
//        try {
            User user = userService.login(username, password);
            session.setAttribute(CommonConstants.LOGIN_USER, user);
        User user1 = null;
        user1.getPassword();
            return new AjaxResult<>(user);
//        } catch (LoginException e) {
//            log.warn("【登录失败】");
//            log.warn(e.getMessage());
//            return new AjaxResult<>(403,e.getMessage());
//        }
    }
    @GetMapping(value = "logout")
    public String logout(HttpSession session) throws LoginException {
        session.removeAttribute(CommonConstants.LOGIN_USER);
        return "redirect:/";
    }

    @PostMapping("upload")
    @ResponseBody
    public AjaxResult<String> upload(MultipartFile file) {
        if (file.isEmpty()) {
            return new AjaxResult<>(400,"请选择文件");
        }
        // 文件上传的操作
        File folder = new File(uploadConfig.getUploadPath() + "avatar/20/2021-06-30");
        folder.mkdirs();
        File targetFile = new File(uploadConfig.getUploadPath()+"avatar/20/2021-06-30/"+file.getOriginalFilename());
        try {
            file.transferTo(targetFile);
            return new AjaxResult<>(uploadConfig.getUploadPrefix()+"avatar/20/2021-06-30/"+file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return new AjaxResult<>(500,"文件上传失败");
        }
    }

    @RequestMapping("detail")
    public String detail() {
        return "user/detail";
    }
}
